import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:zentoon_flutter/theme/app_theme.dart';
import 'package:zentoon_flutter/utils/http_helper.dart';

import '../../providers/comic_detail_provider.dart';
import '../../utils/user_manager.dart';
import '../../widgets/login_dialog.dart';
import '../../widgets/purchase_bottom_sheet.dart';

import '../widget/manhua_list_item.dart';
import 'home_item.dart';
import 'model/comic_detail_model.dart';

class ComicDetailPage extends ConsumerWidget {
  final String comicId;
  const ComicDetailPage({super.key, required this.comicId});

  // Show bottom popup menu
  void _showReportBottomSheet(BuildContext context) {
    showModalBottomSheet(
      context: context,
      // Remove default rounded corners and shadow
      backgroundColor: Colors.transparent,
      // Allow full screen height
      isScrollControlled: true,
      // Animation transition
      transitionAnimationController: AnimationController(
        vsync: Navigator.of(context),
        duration: const Duration(milliseconds: 300),
      ),
      builder: (context) => const ReportSheetContent(),
    );
  }

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final comicDetailAsync = ref.watch(comicDetailProvider(comicId));

    return Scaffold(
      backgroundColor: Color(0xFF211839),
      body: Stack(
        children: [
          // Background image
          Positioned(
            top: 0,
            left: 0,
            right: 0,
            height: 120 + 32 + MediaQuery.of(context).padding.top + 44,
            child: comicDetailAsync.when(
              data: (comicDetail) => CachedNetworkImage(
                imageUrl: comicDetail.comic?.cover ?? '',
                fit: BoxFit.cover,
                placeholder: (context, url) => Container(
                  color: const Color(0xFF2A1F3D),
                  child: const Center(
                    child: CircularProgressIndicator(
                      valueColor:
                          AlwaysStoppedAnimation<Color>(Color(0xFF8A7CA8)),
                      strokeWidth: 2.0,
                    ),
                  ),
                ),
                errorWidget: (context, url, error) => Container(
                  color: const Color(0xFF2A1F3D),
                  child: const Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(Icons.broken_image,
                          color: Color(0xFF8A7CA8), size: 20),
                      SizedBox(height: 2),
                      Text(
                        'Loading failed',
                        style: TextStyle(
                          color: Color(0xFF8A7CA8),
                          fontSize: 8,
                        ),
                      ),
                    ],
                  ),
                ),
                fadeInDuration: const Duration(milliseconds: 300),
              ),
              loading: () => Container(
                color: const Color(0xFF2A1F3D),
                child: const Center(
                  child: CircularProgressIndicator(
                    valueColor:
                        AlwaysStoppedAnimation<Color>(Color(0xFF8A7CA8)),
                    strokeWidth: 2.0,
                  ),
                ),
              ),
              error: (error, stack) => Container(
                color: const Color(0xFF2A1F3D),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    const Icon(Icons.error_outline,
                        color: Color(0xFF8A7CA8), size: 40),
                    const SizedBox(height: 8),
                    const Text(
                      'Failed to load image',
                      style: TextStyle(
                        color: Color(0xFF8A7CA8),
                        fontSize: 12,
                      ),
                    ),
                    const SizedBox(height: 8),
                    ElevatedButton(
                      onPressed: () {
                        ref.refresh(comicDetailProvider(comicId));
                      },
                      style: ElevatedButton.styleFrom(
                        backgroundColor: const Color(0xFF8A7CA8),
                        padding: const EdgeInsets.symmetric(
                            horizontal: 16, vertical: 8),
                      ),
                      child: const Text(
                        'Retry',
                        style: TextStyle(color: Colors.white, fontSize: 12),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
          // Top navigation bar
          Positioned(
            top: MediaQuery.of(context).padding.top,
            left: 0,
            right: 0,
            height: 44,
            child: Container(
              alignment: Alignment.centerLeft,
              color: Colors.transparent,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  IconButton(
                    icon: const Icon(Icons.arrow_back, color: Colors.white),
                    onPressed: () => Navigator.of(context).pop(),
                  ),
                  IconButton(
                    icon: const Icon(Icons.more_horiz_outlined,
                        color: Colors.white),
                    onPressed: () => {
                      // Show bottom popup menu for report and cancel
                      _showReportBottomSheet(context),
                    },
                  ),
                ],
              ),
            ),
          ),
          // Main content
          // 主内容区域（包含底部按钮）
          Positioned(
              left: 0,
              top: MediaQuery.of(context).padding.top + 44,
              right: 0,
              bottom: 0,
              child: comicDetailAsync.when(
                data: (comicDetail) => Column(
                  children: [
                    // 主要内容区域
                    Expanded(
                      child: _buildContent(context, comicDetail, ref),
                    ),
                  ],
                ),
                loading: () => _buildLoadingState(),
                error: (error, stack) => _buildErrorState(context, ref),
              )),
          // 根据数据状态动态显示底部按钮
          Positioned(
            left: 0,
            right: 0,
            bottom: 0,
            child: comicDetailAsync.when(
              data: (comicDetail) => Container(
                padding: const EdgeInsets.symmetric(horizontal: 16),
                height: 96,
                width: double.infinity,
                color: const Color(0xFF2A1F3D),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    // First button: Favorite
                    Expanded(
                      child: Consumer(
                        builder: (context, ref, child) {
                          final isFavorited = ref
                              .watch(comicDetailProvider(comicId).notifier)
                              .isFavorited;

                          return ElevatedButton.icon(
                            icon: Icon(
                              isFavorited
                                  ? Icons.favorite
                                  : Icons.favorite_border,
                              color: Colors.white,
                              size: 20,
                            ),
                            label: Text(
                              isFavorited ? 'Favorited' : 'Favorite',
                              style: const TextStyle(
                                color: Colors.white,
                                fontSize: 16,
                              ),
                            ),
                            style: ElevatedButton.styleFrom(
                              backgroundColor: isFavorited
                                  ? const Color(0xFFE91E63) // 粉色表示已收藏
                                  : const Color(0xFF211839), // 原色表示未收藏
                              padding: const EdgeInsets.symmetric(
                                  horizontal: 16, vertical: 12),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(30),
                                side: const BorderSide(
                                  color: Colors.white70,
                                  width: 1,
                                ),
                              ),
                              elevation: 2,
                              shadowColor: Colors.black12,
                            ),
                            onPressed: isFavorited
                                ? null // 已收藏时禁用按钮
                                : () async {
                                    final isLoggedIn =
                                        await UserManager.isLoggedIn();
                                    if (isLoggedIn) {
                                      print("添加收藏");
                                      // 调用收藏API
                                      final success = await ref
                                          .read(comicDetailProvider(comicId)
                                              .notifier)
                                          .addToFavorites();

                                      if (success) {
                                        ScaffoldMessenger.of(context)
                                            .showSnackBar(
                                          SnackBar(
                                              content: Text(
                                                  'Added to favorites: ${comicDetail.comic?.title ?? "Unknown comic"}')),
                                        );
                                      } else {
                                        ScaffoldMessenger.of(context)
                                            .showSnackBar(
                                          const SnackBar(
                                              content: Text(
                                                  'Failed to add to favorites, please try again')),
                                        );
                                      }
                                    } else {
                                      showDialog(
                                        context: context,
                                        barrierDismissible: false,
                                        builder: (context) =>
                                            const LoginDialog(),
                                      );
                                    }
                                  },
                          );
                        },
                      ),
                    ),
                    const SizedBox(width: 20),
                    // Second button: Read Now
                    Expanded(
                      child: ElevatedButton.icon(
                        icon: const Icon(
                          Icons.book,
                          color: Colors.white,
                          size: 20,
                        ),
                        label: const Text(
                          'Read Now',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 16,
                          ),
                        ),
                        style: ElevatedButton.styleFrom(
                          backgroundColor: AppTheme.buttonBgColor,
                          padding: const EdgeInsets.symmetric(
                              horizontal: 16, vertical: 12),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(30),
                          ),
                          elevation: 2,
                          shadowColor: Colors.black12,
                        ),
                        onPressed: () {
                          Navigator.of(context).pop();
                          // 跳转到阅读页面
                          // if (comicDetail.comicChapters != null &&
                          //     comicDetail.comicChapters!.isNotEmpty) {
                          //   final chapter = comicDetail.comicChapters!.first;
                          //   if (chapter.chapterId != null) {
                          //     context.pushNamed(
                          //       'direct_reader', // 使用正确的路由名称
                          //       pathParameters: {
                          //         'chapterId': chapter.chapterId!,
                          //       },
                          //     );
                          //   }
                          // } else {
                          //   ScaffoldMessenger.of(context).showSnackBar(
                          //     const SnackBar(
                          //         content: Text(
                          //             'No chapters available for reading')),
                          //   );
                          // }
                        },
                      ),
                    ),
                  ],
                ),
              ),
              loading: () => Container(
                height: 96,
                color: const Color(0xFF2A1F3D),
                child: const Center(
                  child: CircularProgressIndicator(
                    valueColor:
                        AlwaysStoppedAnimation<Color>(Color(0xFF8A7CA8)),
                    strokeWidth: 2.0,
                  ),
                ),
              ),
              error: (error, stack) => Container(
                height: 96,
                color: Color(0xFF2A1F3D),
                child: const Center(
                  child: Text(
                    '加载失败',
                    style: TextStyle(
                      color: Color(0xFF8A7CA8),
                      fontSize: 14,
                    ),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildContent(
      BuildContext context, ComicDetailModel comicDetail, WidgetRef ref) {
    return SingleChildScrollView(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const SizedBox(height: 16),
                ManhListItem(comic: comicDetail.comic),
                const SizedBox(height: 16),
                SizedBox(
                  width: double.infinity,
                  height: 112,
                  child: Stack(
                    children: [
                      Positioned(
                        left: 0,
                        right: 0,
                        top: 32,
                        child: Container(
                          padding: const EdgeInsets.all(16),
                          decoration: BoxDecoration(
                            color: Color(0xFF211839),
                            borderRadius: BorderRadius.circular(12),
                            border: Border.all(color: Colors.white24),
                          ),
                          height: 80,
                          child: const Column(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                "JOIN Premium",
                                style: TextStyle(
                                    color: Colors.white,
                                    fontWeight: FontWeight.bold),
                              ),
                              SizedBox(height: 4),
                              Text(
                                "Unlimited Reading Comics",
                                style: TextStyle(
                                    color: Colors.white54, fontSize: 12),
                              ),
                            ],
                          ),
                        ),
                      ),
                      Positioned(
                          right: 16,
                          top: 10,
                          width: 100,
                          child: SizedBox(
                            height: 90,
                            width: 80,
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                Image.asset(
                                  "assets/images/fthy.png",
                                  width: 60,
                                  height: 60,
                                ),
                                GestureDetector(
                                  onTap: () {
                                    // 处理购买按钮点击事件
                                    GoRouter.of(context)
                                        .pushNamed('PremiumScreen');
                                  },
                                  child: Container(
                                    padding: const EdgeInsets.symmetric(
                                        horizontal: 12, vertical: 4),
                                    decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(20),
                                      color: Colors.white,
                                    ),
                                    child: const Text(
                                      "Buy Now",
                                      style: TextStyle(
                                          color: Color(0xFF211839),
                                          fontSize: 12),
                                    ),
                                  ),
                                )
                              ],
                            ),
                          ))
                    ],
                  ),
                ),
                const SizedBox(height: 20),
                Text(
                  comicDetail.comic?.title ?? "NASTY GIRL",
                  style: const TextStyle(color: Colors.white70, fontSize: 16),
                ),
                const SizedBox(height: 30),
                const Text(
                  "Chapters",
                  style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                      color: Colors.white),
                ),
                const SizedBox(height: 16),
                GridView.builder(
                  padding: EdgeInsets.zero,
                  shrinkWrap: true,
                  physics: const NeverScrollableScrollPhysics(),
                  itemCount: comicDetail.comicChapters?.length ?? 8,
                  gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 4,
                    mainAxisSpacing: 8,
                    crossAxisSpacing: 8,
                    childAspectRatio: 2.2,
                  ),
                  itemBuilder: (shareContext, index) {
                    final chapter = comicDetail.comicChapters?[index];
                    final isLocked = chapter?.isBuy ==
                        true; // Simulate first 3 open, rest locked

                    return GestureDetector(
                      onTap: () async {
                        print("sdfsdsfsd");
                        if (chapter != null && chapter.chapterId != null) {
                          print("判断是否购买了章节: ${chapter.isBuy}");
                          if (chapter.isBuy == false) {
                            // 跳转到阅读页面
                            context.pushNamed(
                              'direct_reader',
                              pathParameters: {
                                'chapterId': chapter.chapterId ?? "",
                                'comicId': comicDetail.comic?.id ?? '',
                              },
                            );
                          } else {
                            final isLoggedIn = await UserManager.isLoggedIn();
                            if (isLoggedIn) {
                              // Show purchase bottom sheet
                              PurchaseBottomSheet.show(shareContext,
                                  chapterTitle: chapter.chapterTitle ??
                                      "Chapter ${index + 1}",
                                  chapterPrice: comicDetail
                                          .buyPrice?.chapterPrice ??
                                      50, // Replace with actual chapter price
                                  comicPrice: comicDetail
                                          .buyPrice?.comicPrice ??
                                      200, // Replace with actual comic price
                                  comicTitle:
                                      comicDetail.comic?.title ?? "This Comic",
                                  onPurchaseChapter: () async {
                                // Handle chapter purchase
                                print('🔥🔥🔥 onPurchaseChapter 被调用了！');
                                // Handle chapter purchase
                                print('Purchase chapter: ${chapter.chapterId}');
                                // Add your chapter purchase logic here
                                EasyLoading.show();
                                try {
                                  print('🚀 准备发送HTTP请求...');
                                  final response = await HttpUtil().postJson(
                                    'ComicMember/BuyComic',
                                    data: {
                                      "id": chapter.chapterId,
                                      "isAllBuyChapter": false
                                    },
                                  );
                                  print("✅ 购买章节接口返回: $response");
                                  EasyLoading.dismiss();
                                  if (response?['status'] == 200) {
                                    EasyLoading.showToast(
                                        "Purchase completed successfully");
                                    // ref
                                    //     .read(comicDetailProvider(comicId)
                                    //         .notifier)
                                    // .refresh();
                                    ref.refresh(comicDetailProvider(comicId));
                                  } else {
                                    if (response?['status'] == 400) {
                                      _showBalanceInsufficientDialog(context);
                                    } else {
                                      EasyLoading.showToast(
                                          response?['message']);
                                    }
                                  }
                                } catch (e) {
                                  print('❌ 购买请求异常: $e');
                                  EasyLoading.dismiss();
                                  EasyLoading.showToast("Purchase failed: $e");
                                }
                              }, onPurchaseComic: () async {
                                EasyLoading.show();
                                try {
                                  print('🚀 准备发送HTTP请求...');
                                  final response = await HttpUtil().postJson(
                                    'ComicMember/BuyComic',
                                    data: {
                                      "id": comicDetail.comic?.id ?? '',
                                      "isAllBuyChapter": true
                                    },
                                  );
                                  print("✅ 购买章节接口返回: $response");
                                  EasyLoading.dismiss();
                                  if (response?['status'] == 200) {
                                    EasyLoading.showToast(
                                        "Purchase completed successfully");
                                    // ref
                                    //     .read(comicDetailProvider(comicId)
                                    //         .notifier)
                                    // .refresh();
                                    ref.refresh(comicDetailProvider(comicId));
                                  } else {
                                    if (response?['status'] == 400) {
                                      _showBalanceInsufficientDialog(context);
                                    } else {
                                      EasyLoading.showToast(
                                          response?['message']);
                                    }
                                  }
                                } catch (e) {
                                  print('❌ 购买请求异常: $e');
                                  EasyLoading.dismiss();
                                  EasyLoading.showToast("Purchase failed: $e");
                                }
                              }, onSubscribePremium: () {
                                print("刷新数据asdasda");
                                // GoRouter.of(context).pushNamed('PremiumScreen');
                                ref.refresh(comicDetailProvider(comicId));
                              });
                            } else {
                              showDialog(
                                context: context,
                                barrierDismissible: false,
                                builder: (context) => const LoginDialog(),
                              );
                            }
                          }
                        }
                      },
                      child: Container(
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                          color: isLocked
                              ? Colors.deepPurple.shade700
                                  .withValues(alpha: 0.3)
                              : Colors.deepPurple.shade100,
                          borderRadius: BorderRadius.circular(6),
                          border: Border.all(color: Colors.white24),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text(chapter?.chapterTitle ?? "Act ${index + 1}",
                                style: TextStyle(
                                    fontSize: 12,
                                    color: isLocked
                                        ? Colors.white54
                                        : Colors.black)),
                            if (isLocked)
                              const Icon(Icons.lock,
                                  size: 14, color: Colors.white54),
                          ],
                        ),
                      ),
                    );
                  },
                ),
                const SizedBox(height: 32),
                const Text(
                  "Similar Comics",
                  style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                      color: Colors.white),
                ),
              ],
            ),
          ),
          const SizedBox(height: 12),
          TwoByThreeGridDemo(similarComic: comicDetail.similarComic),
          const SizedBox(height: 20),
        ],
      ),
    );
  }

  void _showBalanceInsufficientDialog(BuildContext context) {
    showDialog(
      context: context,
      barrierDismissible: true,
      builder: (context) => Dialog(
        backgroundColor: Colors.transparent,
        child: Container(
          width: MediaQuery.of(context).size.width * 0.85,
          decoration: BoxDecoration(
            gradient: const LinearGradient(
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
              colors: [
                Color(0xFF2D1B69),
                Color(0xFF1A0E3D),
              ],
            ),
            borderRadius: BorderRadius.circular(20),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.3),
                blurRadius: 20,
                offset: const Offset(0, 10),
              ),
            ],
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // Header
              Container(
                padding: const EdgeInsets.all(24),
                child: const Column(
                  children: [
                    Icon(
                      Icons.account_balance_wallet_outlined,
                      color: Colors.amber,
                      size: 56,
                    ),
                    SizedBox(height: 16),
                    Text(
                      'Insufficient Balance',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 26,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    SizedBox(height: 12),
                    Text(
                      'You don\'t have enough coins to purchase this chapter. Please top up your account to continue reading.',
                      style: TextStyle(
                        color: Colors.white70,
                        fontSize: 15,
                      ),
                      textAlign: TextAlign.center,
                    ),
                  ],
                ),
              ),

              // Action Buttons
              Padding(
                padding: const EdgeInsets.fromLTRB(24, 0, 24, 24),
                child: Column(
                  children: [
                    // Top Up Button
                    SizedBox(
                      width: double.infinity,
                      child: ElevatedButton.icon(
                        onPressed: () {
                          Navigator.of(context).pop();
                          // Navigate to top up screen
                          context.push('/topup');
                        },
                        icon: const Icon(Icons.add_circle_outline,
                            color: Colors.white),
                        label: const Text(
                          'Top Up Coins',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Color(0xFF4CAF50),
                          padding: const EdgeInsets.symmetric(vertical: 16),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(12),
                          ),
                          elevation: 4,
                        ),
                      ),
                    ),

                    const SizedBox(height: 12),

                    // Go Premium Button
                    SizedBox(
                      width: double.infinity,
                      child: OutlinedButton.icon(
                        onPressed: () {
                          Navigator.of(context).pop();
                          // Navigate to premium screen
                          GoRouter.of(context).pushNamed('PremiumScreen');
                        },
                        icon: const Icon(Icons.workspace_premium,
                            color: Colors.amber),
                        label: const Text(
                          'Go Premium',
                          style: TextStyle(
                            color: Colors.amber,
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        style: OutlinedButton.styleFrom(
                          padding: const EdgeInsets.symmetric(vertical: 16),
                          side: BorderSide(color: Colors.amber, width: 2),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(12),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),

              // Close Button
              Padding(
                padding: const EdgeInsets.fromLTRB(24, 0, 24, 16),
                child: TextButton(
                  onPressed: () => Navigator.of(context).pop(),
                  child: const Text(
                    'Maybe Later',
                    style: TextStyle(
                      color: Colors.white60,
                      fontSize: 15,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildLoadingState() {
    return Container(
      color: const Color(0xFF211839),
      child: const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            CircularProgressIndicator(
              valueColor: AlwaysStoppedAnimation<Color>(Color(0xFF8A7CA8)),
              strokeWidth: 3.0,
            ),
            SizedBox(height: 16),
            Text(
              'Loading comic details...',
              style: TextStyle(
                color: Colors.white70,
                fontSize: 16,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildErrorState(BuildContext context, WidgetRef ref) {
    return Container(
      color: const Color(0xFF211839),
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(
              Icons.error_outline,
              color: Color(0xFF8A7CA8),
              size: 64,
            ),
            const SizedBox(height: 16),
            const Text(
              'Failed to load comic details',
              style: TextStyle(
                color: Colors.white70,
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 8),
            const Text(
              'Please check your internet connection\nand try again',
              textAlign: TextAlign.center,
              style: TextStyle(
                color: Colors.white54,
                fontSize: 14,
              ),
            ),
            const SizedBox(height: 24),
            ElevatedButton.icon(
              onPressed: () {
                ref.refresh(comicDetailProvider(comicId));
              },
              icon: const Icon(Icons.refresh, color: Colors.white),
              label: const Text(
                'Retry',
                style: TextStyle(color: Colors.white, fontSize: 16),
              ),
              style: ElevatedButton.styleFrom(
                backgroundColor: Color(0xFF8A7CA8),
                padding:
                    const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _handlePurchaseChapter(String chapterId) {
    // TODO: Implement chapter purchase logic
    // This should call your payment API
    // ScaffoldMessenger.of(context).showSnackBar(
    //   const SnackBar(
    //     content: Text('Chapter purchase initiated...'),
    //     backgroundColor: Colors.green,
    //   ),
    // );
  }

  // Handle purchase comic
  void _handlePurchaseComic(String comicId) {
    // TODO: Implement comic purchase logic
    // This should call your payment API
    // ScaffoldMessenger.of(context).showSnackBar(
    //   const SnackBar(
    //     content: Text('Comic purchase initiated...'),
    //     backgroundColor: Colors.blue,
    //   ),
    // );
  }

  // Handle premium subscription
  void _handleSubscribePremium() {
    // TODO: Implement premium subscription logic
    // This should navigate to subscription page or call subscription API
    // ScaffoldMessenger.of(context).showSnackBar(
    //   const SnackBar(
    //     content: Text('Premium subscription initiated...'),
    //     backgroundColor: Colors.orange,
    //   ),
    // );
  }
}

// Report menu content
class ReportSheetContent extends StatelessWidget {
  const ReportSheetContent();

  @override
  Widget build(BuildContext context) {
    return Container(
      // Top rounded corners
      decoration: const BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.vertical(
          top: Radius.circular(16),
        ),
      ),
      // Maximum height limit
      constraints: BoxConstraints(
        maxHeight: MediaQuery.of(context).size.height * 0.8,
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // Top indicator
          Padding(
            padding: const EdgeInsets.symmetric(vertical: 12),
            child: Container(
              width: 40,
              height: 4,
              decoration: const BoxDecoration(
                color: Colors.grey,
                borderRadius: BorderRadius.all(Radius.circular(2)),
              ),
            ),
          ),

          // Title
          const Padding(
            padding: EdgeInsets.symmetric(vertical: 16),
            child: Text(
              'Report Content',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
                color: Colors.black87,
              ),
            ),
          ),

          // Report reason list
          const Column(
            children: [
              _ReportReasonItem(
                icon: Icons.warning,
                text: 'Inappropriate Content',
              ),
              _ReportReasonItem(
                icon: Icons.person,
                text: 'Personal Attack',
              ),
              _ReportReasonItem(
                icon: Icons.spa,
                text: 'Spam',
              ),
              _ReportReasonItem(
                icon: Icons.copyright,
                text: 'Copyright Infringement',
              ),
              _ReportReasonItem(
                icon: Icons.other_houses,
                text: 'Other Reasons',
              ),
            ],
          ),

          // Cancel button
          SafeArea(
            child: Padding(
              padding: const EdgeInsets.all(16),
              child: SizedBox(
                width: double.infinity,
                child: ElevatedButton(
                  onPressed: () => Navigator.pop(context),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.grey[200],
                    foregroundColor: Colors.black87,
                    padding: const EdgeInsets.symmetric(vertical: 16),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12),
                    ),
                    elevation: 0,
                  ),
                  child: const Text(
                    'Cancel',
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

// Report reason option
class _ReportReasonItem extends StatelessWidget {
  final IconData icon;
  final String text;

  const _ReportReasonItem({
    required this.icon,
    required this.text,
  });

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: () {
        // Handle report logic
        Navigator.pop(context);
        // Show report success message
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('Reported: $text'),
            behavior: SnackBarBehavior.floating,
          ),
        );
      },
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 18),
        decoration: const BoxDecoration(
          border: Border(
            bottom: BorderSide(
              color: Colors.grey,
              width: 0.5,
            ),
          ),
        ),
        child: Row(
          children: [
            Icon(
              icon,
              color: Colors.red,
              size: 22,
            ),
            const SizedBox(width: 16),
            Text(
              text,
              style: const TextStyle(
                fontSize: 16,
                color: Colors.black87,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
